"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '07/09/2022'
    comment: 自定义radio button
"""
from typing import Callable
from PyQt5.QtWidgets import QRadioButton, QLabel, QSpacerItem, QSizePolicy, QHBoxLayout, QButtonGroup, QWidget
from dataclasses import dataclass

from project.component import TITLE_FONT, CONTENT_FONT


@dataclass
class RadioButton:
    """
    """
    title: str
    object_name: str
    toggle: Callable | None  # 点击事件


class UserRadioButton(QWidget):
    """
    """
    def __init__(self,
                 label_text: str = '',
                 radio_buttons: list[RadioButton] | None = None,
                 default_checked: Callable | None = None,
                 gap=0,
                 parent=None):
        """
        :param label_text:
        :param default_checked: 默认被选中处理
        :param radio_buttons:
        :param gap:
        :param parent:
        """
        super().__init__(parent)
        # 创建子控件
        self.label = QLabel(label_text, self)
        self.label.setFont(TITLE_FONT)

        self.radios = []
        for idx, radio_button in enumerate(radio_buttons):
            radio = QRadioButton(radio_button.title)
            if radio_button.object_name:
                radio.setObjectName(radio_button.object_name)
            if radio_button.toggle is not None:
                radio.toggled.connect(radio_button.toggle)
            radio.setFont(CONTENT_FONT)
            self.radios.append(radio)

        group = QButtonGroup()
        for radio in self.radios:
            group.addButton(radio)

        # 中间弹簧
        self.gap_spacer = QSpacerItem(gap, 0, QSizePolicy.Fixed, QSizePolicy.Minimum)

        # 布局
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)  # 去掉外边距，可自由调整
        layout.addWidget(self.label)
        layout.addItem(self.gap_spacer)
        for radio in self.radios:
            layout.addWidget(radio)

        self.default_checked = default_checked
        self._set_default_checked()

    def _set_default_checked(self):
        """
        :return:
        """
        if self.default_checked is None:
            self.radios[0].setChecked(True)
            return

        object_name = self.default_checked()
        for radio in self.radios:
            if radio.objectName() != object_name:
                continue
            radio.setChecked(True)
